package server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;

public class Server {
	public static HashMap<String, Socket> mapClient = new HashMap<>();
	private ServerSocket serverSocket = null;
	private int port = 2222;
	private Socket clientSocket = null;
	
	public void createServer(){
		try {
			serverSocket = new ServerSocket(port);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void closeServer(){
		try {
			if (serverSocket != null)
				serverSocket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void loop(){
		while(true){
			try {
				clientSocket = serverSocket.accept();
				ClientHandler ch = new ClientHandler(clientSocket, mapClient);
				ch.start();
			} catch (Exception e) {
				e.printStackTrace();
				try {
					if(clientSocket != null)
						clientSocket.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
				closeServer();
			}
		}
	}
	
	public static void main(String[] args) {
		Server sv = new Server();
		sv.createServer();
		System.out.println("Tao server thanh cong");
		sv.loop();
	}
}
